/*
 * @Author: 缄默
 * @Date: 2021-12-12 15:17:32
 * @LastEditors: 缄默
 * @LastEditTime: 2021-12-26 16:21:44
 */

//备忘录模式

#include <iostream>
#include <vector>
#include <string>
#include <stack>

using namespace std;

//备忘录类 所有成员均为私有
class Memento {
private:
    string _state;

private:
   friend class Originator;
    Memento(string& state) {
        _state = state;
    }

    void setState(string& state) {
        _state = state;
    }

    string getState() {
        return _state;
    }
};

//存储管理备忘录
class Caretaker {
private:
    stack<Memento*> _memento;

public:
    void setMemento(Memento* memento) {
        _memento.push(memento);
    }

    Memento* getMemento() {
        Memento* res = _memento.top();
        _memento.pop();
        return res;
    }
};

//备忘录发起者
class Originator {
private:
    string _state;
    Caretaker _caretaker;

    void createMemento() {
        Memento* mem = new Memento(_state);
        _caretaker.setMemento(mem);
    }

    Originator() { }
    
public:

    Originator(string& state) {
        _state = state;
    }
    
    string getState() {
        return _state;
    }

    void setState(string& state) {
        createMemento();
        _state = state;
    }

    void RestoreToMemento() {
        Memento* mem = _caretaker.getMemento();
        _state = mem->getState();
    }

    void printState() {
        cout << _state << endl;
    }
};


int main() {
    string str1 = "old";
    string str2 = "new1";
    string str3 = "new2";


    Originator* originator = new Originator(str1);
    originator->printState();
    originator->setState(str2);
    originator->printState();
    originator->setState(str3);
    originator->printState();
    originator->RestoreToMemento();
    originator->printState();
    originator->RestoreToMemento();
    originator->printState();
    delete originator;

    return 0;
}


